package messageservice

import (
	"encoding/json"
	"log"
	"math/rand"
	"net"
	"os"
	"strconv"
	"time"
)

// rand32
func CreateUUID32() string {
	var str = ""
	for i := 0; i < 32; i++ {
		var n = rand.Intn(32)
		str += strconv.Itoa(n)
	}
	str += strconv.FormatInt(time.Now().Local().Unix(), 16)
	return str
}

// rand10
func CreateUUID() string {
	var str = ""
	for i := 0; i < 10; i++ {
		var n = rand.Intn(10)
		str += strconv.Itoa(n)
	}
	str += strconv.FormatInt(time.Now().Local().Unix(), 16)
	return str
}

// 强制getlocalip为某个公网IP或怎么样的
var RecordAddr = ""
var localAddr []string = nil

func GetLocalIp() []string {
	if RecordAddr != "" {
		return []string{RecordAddr}
	}
	if localAddr != nil {
		return localAddr
	}
	name, err := os.Hostname()
	if err != nil {
		log.Println("获取IP错误", err)
		return nil
	}
	iplist, err := net.LookupIP(name)
	if err != nil {
		log.Println("获取IP错误", err)
		return nil
	}
	var list = make([]string, len(iplist))
	var i = 0
	for _, addr := range iplist {
		if ipv4 := addr.To4(); ipv4 != nil {
			if ipv4.String() != "" {
				list[i] = ipv4.String()
				i = i + 1
			}
		}
	}

	localAddr = list[0:i]
	return localAddr
}

// 字典转存构体数据
func MapToStruct(mapdata any, structdata any) error {
	buff, err := json.Marshal(mapdata)
	if err != nil {
		return err
	}
	err = json.Unmarshal(buff, structdata)
	if err != nil {
		return err
	}
	return nil
}
